package com.tich.interceptors;

import cn.hutool.core.util.StrUtil;
import com.tich.constant.RequestConstant;
import com.tich.context.UserContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 用户信息拦截器，用于获取从网关传来的userId，并存入threadLocal中
 * */
public class UserInfoInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取用户登录信息
        String userInfo = request.getHeader(RequestConstant.USER_INFO);
        //判断是否有用户信息，如果有则存入threadLocal
        if(StrUtil.isNotBlank(userInfo)){
            UserContext.setCurrentId(Long.valueOf(userInfo));
        }
        //直接放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //删除用户线程
        UserContext.removeCurrentId();
    }
}
